package com.example.fan.airline_reservation;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.bin.david.form.data.style.FontStyle;
import com.example.fan.airline_reservation.Adapter.FightAdapter;
import com.example.fan.airline_reservation.Model.Fight;
import com.example.fan.airline_reservation.Model.Order;
import com.example.fan.airline_reservation.Model.USER;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.datatype.BmobQueryResult;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SQLQueryListener;
import cn.bmob.v3.listener.UpdateListener;
import cn.pedant.SweetAlert.SweetAlertDialog;

public class ac_to_modifyfight extends AppCompatActivity {

    int[] delay_time=new int[]{15,30,45,60,90,180,0};
    String[] pmodel=new String[]{"C191(中)","空客320(中)",
                                    "空客321(中)","空客330(大)",
                                    "波音737(中)","波音787(大)","庞巴迪900(小)"};

    TextView month_day,week,fromTo;
    TextView info,go_off,arrival_time;
    TextView departure,termini;
    TextView state;
    Spinner sp_1,sp_2;
    int bigChoose=0,DT=0;
    TextView sc;
    Button submit;
    String newModel;
    double newPrice;

    /*detail内容*/
    TextView seat;
    Button detail;

    /*退款内容*/
    long up,down;
    List<UM> listUM=new ArrayList<UM>();
    public static final int UPDATE = 1;
    List<USER> u = new ArrayList<USER>();
    public static final int FINALDB = 2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ac_to_modifyfight);
        /*不显示bar*/
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }

        Intent intent=getIntent();
        final Fight fight = (Fight)getIntent().getSerializableExtra("FightInfo");

        /*日期范围*/
        int year,month,day;
        year=fight.getDATE().getYear();
        month=fight.getDATE().getMonth();
        day=fight.getDATE().getDate();
        Date date=new Date(year,month,day-1,23,59,59);
        Date date1=new Date(year,month,day+1,0,0,0);
        up=date.getTime();
        down=date1.getTime();

        month_day=(TextView)findViewById(R.id.month_day);
        month_day.setText(fight.getDATE().getMonth()+"-"+fight.getDATE().getDate());
        week=(TextView)findViewById(R.id.week);
        week.setText(numToWeek(fight.getDATE().getDay()));
        fromTo=(TextView)findViewById(R.id.fromTo);
        fromTo.setText(fight.getFROM()+"➟"+fight.getTO());
        info=(TextView)findViewById(R.id.info);
        info.setText(fightToACName(fight.getFLIGHT())+" "+fight.getFLIGHT()+" "+fight.getAIRCRAFT_MODEL());
        state=(TextView)findViewById(R.id.state2);
        /*设置航班状态*/
        switch (fight.getCurrentState()){
            case 0: {
                state.setText("准点");
                state.setTextColor(Color.GREEN);
                break;
            }
            case 1:{
                state.setText("延误"+fight.getDelayTime()+"分钟");
                state.setTextColor(Color.parseColor("#FFA500"));
                break;
            }
        }

        go_off=(TextView)findViewById(R.id.go_off1);
        arrival_time=(TextView)findViewById(R.id.arrival_time1);
        int hour,min,hour1,min1;
        hour=fight.getDATE().getHours();
        hour1=fight.getTODATE().getHours();
        min=fight.getDATE().getMinutes();
        min1=fight.getTODATE().getMinutes();
        String time=String.valueOf(hour)+":"+String.valueOf(min);
        String time1=String.valueOf(hour1)+":"+String.valueOf(min1);
        go_off.setText(time);
        arrival_time.setText(time1);

        departure=(TextView)findViewById(R.id.departure1);
        termini=(TextView)findViewById(R.id.termini1);
        departure.setText(fight.getFROMNAME());
        termini.setText(fight.getTONAME());

        sp_1=(Spinner)findViewById(R.id.operate_type_1);
        sp_2=(Spinner)findViewById(R.id.operate_type_2);
        sc=(TextView)findViewById(R.id.smallLabel);
        sp_1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                bigChoose=position;
                sc.setClickable(false);
                switch (position) {
                    case 0: {
                        sc.setVisibility(View.VISIBLE);
                        sp_2.setVisibility(View.VISIBLE);
                        String[] data = getResources().getStringArray(R.array.delay);
                        ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, data);
                        sp_2.setAdapter(Adapter);
                        sc.setText("请选择延误时间");
                        break;
                    }
                    case 1:{
                        sc.setVisibility(View.VISIBLE);
                        sp_2.setVisibility(View.VISIBLE);
                        String[] data = getResources().getStringArray(R.array.AIRCRAFT_MODEL);
                        ArrayAdapter<String> Adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item, data);
                        sp_2.setAdapter(Adapter);
                        sc.setText("请选择新的执飞机型");
                        break;
                    }
                    case 2:{
                        sc.setVisibility(View.GONE);
                        sp_2.setVisibility(View.GONE);
                        break;
                    }
                    case 3:{
                        sc.setVisibility(View.VISIBLE);
                        sp_2.setVisibility(View.VISIBLE);
                        sc.setText("请输入新的票价");
                        sp_2.setVisibility(View.GONE);
                        sc.setClickable(true);
                        sc.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                AlertDialog.Builder builder = new AlertDialog.Builder(ac_to_modifyfight.this);
                                builder.setTitle("请输入新的价格");
                                final EditText newTime = new EditText(ac_to_modifyfight.this);
                                builder.setView(newTime);
                                builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        newPrice = Double.parseDouble(newTime.getText().toString());
                                        sc.setText("新价格："+newPrice);
                                    }
                                });
                                builder.show();
                            }
                        });
                        break;
                    }
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        sp_2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            /*选择延误时间和更换执飞机型*/
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (bigChoose==0) {
                    DT=position;
                    if (position == 6) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(ac_to_modifyfight.this);
                        builder.setTitle("请输入延误时间");
                        final EditText newTime = new EditText(ac_to_modifyfight.this);
                        builder.setView(newTime);
                        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                delay_time[6] = Integer.parseInt(newTime.getText().toString());
                            }
                        });
                        builder.show();
                    }
                }else if (bigChoose==1){
                    newModel=pmodel[position];
                }else if (bigChoose==3){

                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        submit=(Button)findViewById(R.id.modify_submit);
        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new SweetAlertDialog(ac_to_modifyfight.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("您确定要修改么?")
                        .setConfirmText("确认提交!")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                /*修改航班状态*/
                                SubmitInfo(fight);
                                sDialog.setTitleText("修改成功")
                                        .setConfirmText("OK")
                                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                            @Override
                                            public void onClick(SweetAlertDialog sweetAlertDialog) {
                                                finish();
                                            }
                                        })
                                        .changeAlertType(SweetAlertDialog.SUCCESS_TYPE);
                            }
                        })
                        .show();
            }
        });

        seat=(TextView)findViewById(R.id.seat);
        detail=(Button)findViewById(R.id.details);
        double info= fight.getCurrentPeole()/Double.parseDouble(modelToNum(fight.getAIRCRAFT_MODEL()));
        seat.setText(String.format("订票率："+"%.2f", info)+"%");
        detail.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ac_to_modifyfight.this, Detail.class);
                intent.putExtra("FightInfo",fight);
                startActivity(intent);
            }
        });
    }

    public void SubmitInfo(final Fight fight){
        if (bigChoose == 2) {
            fight.setCurrentState(2);
            fight.update(fight.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ToastShow("取消航班成功");
                    } else {
                        ToastShow("取消延误失败");
                    }
                }
            });
            drawback(fight.getFLIGHT());
        } else if (bigChoose == 0) {
            fight.setCurrentState(1);
            fight.setDelayTime(fight.getDelayTime() + delay_time[DT]);
            fight.update(fight.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ToastShow("设置延误成功");
                    } else {
                        ToastShow("设置延误失败");
                    }
                }
            });
        } else if (bigChoose == 1) {
            fight.setAIRCRAFT_MODEL(newModel);
            fight.update(fight.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ToastShow("更换执飞机型成功");
                    } else {
                        ToastShow("更换执飞机型失败");
                    }
                }
            });
        }else if (bigChoose == 3) {
            fight.setPRICE(newPrice);
            fight.update(fight.getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                    if (e == null) {
                        ToastShow("修改价格成功");
                    } else {
                        ToastShow("修改价格失败");
                    }
                }
            });
        }
    }

    /*星期几转换*/
    public String numToWeek(int i){
        switch (i){
            case 0:return "周一";
            case 1:return "周二";
            case 2:return "周三";
            case 3:return "周四";
            case 4:return "周五";
            case 5:return "周六";
            case 6:return "周日";
            default: return " ";
        }
    }

    /*航班号->航空公司名称*/
    public String fightToACName(String fight){
        if (fight.contains("MU")){
            return "东航";
        }else if (fight.contains("CZ")){
            return "南航";
        }else if (fight.contains("HO")){
            return "吉祥";
        }else if (fight.contains("3U")){
            return "川航";
        }else if (fight.contains("CA")){
            return "国航";
        }else if (fight.contains("HU")){
            return "海航";
        }else if (fight.contains("9C")){
            return "春秋";
        }else {
            return "未知航司";
        }
    }

    public void ToastShow(String message){
        Toast.makeText(ac_to_modifyfight.this,message,Toast.LENGTH_SHORT).show();
    }

    /*型号->人数*/
    public String modelToNum(String plane){
        switch (plane){
            case "C191(中)": return "168";
            case "空客320(中)": return "180";
            case "空客321(中)": return "180";
            case "空客330(大)": return "350";
            case "波音737(中)": return "160";
            case "波音787(大)": return "400";
            case "庞巴迪900(小)": return "86";
            default:return "未知";
        }
    }

    /*退款内容*/
    public void drawback(String flight){

        String bq = "select * from Order where fight = '"+flight+"' "+
                "and date > "+up+" "+
                "and date < "+down+"order by account";
        new BmobQuery<Order>().doSQLQuery(bq,new SQLQueryListener<Order>(){
            @Override
            public void done(BmobQueryResult<Order> result, BmobException e) {
                if(e ==null){
                    List<Order> list = (List<Order>) result.getResults();
                    Log.d("test", list.size()+"");
                    if(list!=null && list.size()>0){
                         for (int i=0;i<list.size();i++) {
                             if (listUM.size()==0){
                                 listUM.add(new UM(list.get(i).getAccount(),list.get(i).getPrice()));
                             }else {
                                 int j;
                                 for(j=0;j<listUM.size();j++){
                                     if (listUM.get(j).getName().equals(list.get(i).getAccount())){
                                         listUM.get(j).setMoney(listUM.get(j).getMoney()+list.get(i).getPrice());
                                         break;
                                     }
                                 }
                                 if (j==listUM.size()){
                                     listUM.add(new UM(list.get(i).getAccount(),list.get(i).getPrice()));
                                 }
                             }
                         }
                         Message message = new Message();
                         message.what = UPDATE;
                         message.obj = listUM;
                         handler.sendMessage(message);
                        Log.d("test", "after sendmessage");
                    }
                }else{
                    Log.d("test", "错误码："+e.getErrorCode()+"，错误描述："+e.getMessage());
                    ToastShow("错误码："+e.getErrorCode()+"，错误描述："+e.getMessage());
                }
            }
        });
    }

    class UM{
        private String name;
        private double money;

        public UM(String name, double money) {
            this.name = name;
            this.money = money;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public double getMoney() {
            return money;
        }
        public void setMoney(double money) {
            this.money = money;
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case UPDATE:{
                    listUM = (List<UM>)msg.obj;
                    goDrawback();
                    break;
                }
                case FINALDB:{
                    u = (List<USER>)msg.obj;
                    goFinish();
                    break;
                }
                default:break;
            }
        }
    };

    public void goDrawback(){
        String bq ="select * from USER where";
        for (int i = 0;i<listUM.size()-1;i++){
            bq+=" name = '"+listUM.get(i).getName()+"' or";
        }
        bq+=" name = '"+listUM.get(listUM.size()-1).getName()+"' order by name";
        new BmobQuery<USER>().doSQLQuery(bq,new SQLQueryListener<USER>(){
            @Override
            public void done(BmobQueryResult<USER> result, BmobException e) {
                if(e ==null){
                    List<USER> list = (List<USER>) result.getResults();
                    Message message = new Message();
                    message.what=FINALDB;
                    message.obj=list;
                    handler.sendMessage(message);
                }else{
                    ToastShow("错误码："+e.getErrorCode()+"，错误描述："+e.getMessage());
                }
            }
        });
    }

    public void goFinish(){
        int i = 0;
        for(;i<u.size();i++){
            u.get(i).setMoney(u.get(i).getMoney()+listUM.get(i).getMoney());
            u.get(i).update(u.get(i).getObjectId(), new UpdateListener() {
                @Override
                public void done(BmobException e) {
                }
            });
        }
        ToastShow("退款成功！");
    }

}
